#include <stdio.h>
#include <stdint.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>

typedef struct {
    char sign[2];
    char unit[4];
    uint8_t decimal;
    double net_weight;
    char stability[16];
    double tare;
} Command20Result;

int parse_cmd20(const uint8_t *data, size_t len, Command20Result *result) {
    // 基础校验
    if (len != 15) return -1;
    if (data[0] != 0xAA || data[14] != 0x2F) return -2;

    // 校验和验证
    uint8_t checksum = 0;
    for (int i = 0; i < 13; i++) checksum += data[i];
    checksum %= 256;
    if (checksum != data[13]) return -3;

    // 解析正负和单位
    switch (data[3]) {
        case 0x81: 
            snprintf(result->sign, sizeof(result->sign), "+");
            snprintf(result->unit, sizeof(result->unit), "KG");
            break;
        case 0x01:
            snprintf(result->sign, sizeof(result->sign), "-");
            snprintf(result->unit, sizeof(result->unit), "KG");
            break;
        default: return -4;
    }

    // 解析小数位
    result->decimal = data[4];

    // 解析净重（大端序）
    uint32_t net_weight_raw = (data[5] << 24) | (data[6] << 16) | (data[7] << 8) | data[8];
    result->net_weight = (double)net_weight_raw / pow(10, result->decimal);

    // 稳定状态
    if (data[9] == 0x0A) snprintf(result->stability, sizeof(result->stability), "稳定");
    else snprintf(result->stability, sizeof(result->stability), "不稳定");

    // 解析皮重（3字节大端序）
    uint32_t tare_raw = (data[10] << 16) | (data[11] << 8) | data[12];
    result->tare = (double)tare_raw / pow(10, result->decimal);

    return 0;
}



int main() {
    // 测试数据: AA 0B 20 81 03 00 00 02 76 0A 00 00 00 DB 2F
    uint8_t data[] = {
     0xAA,0x0B,0x20,0x81,0x03,0x00,0x00,0x02,0x76,0x0A,0x00,0x00,0x00,0xDB,0x2F
    };

//转化数据
    // const char* hex_str = "AA 0B 27 00 00 00 00 00 00 00 02 81 01 00 60 2F";
    // size_t count = 0;
    // uint8_t data[16]; // 假设我们知道数据长度为16
    // hex_str_to_bytes(hex_str, data, &count);
    // 打印结果
    // for (size_t i = 0; i < count; i++) {
    //     printf("0x%02X ", data[i]);
    // }

    Command20Result result;
    int ret = parse_cmd20(data, sizeof(data), &result);
    if (ret != 0) {
        printf("解析失败，错误码：%d\n", ret);
        return -1;
    }

    printf("解析结果：\n");
    printf("符号+单位: %s%s\n", result.sign, result.unit);
    printf("小数位: %d\n", result.decimal);
    printf("净重: %.*f %s\n", result.decimal, result.net_weight, result.unit);
    printf("稳定状态: %s\n", result.stability);
    printf("皮重: %.*f %s\n", result.decimal, result.tare, result.unit);

    return 0;
}
//  gcc -o jiexi jiexi.c && jiexi.exe
